const jwt = require('jsonwebtoken')
const { User } = require('../models')

const auth = async (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1]
    
    if (!token) {
      return res.status(401).json({ message: '未提供token' })
    }
    
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    const user = await User.findByPk(decoded.userId)
    
    if (!user || !user.isActive) {
      return res.status(401).json({ message: '用户不存在或已被禁用' })
    }
    
    req.user = user
    next()
  } catch (error) {
    res.status(401).json({ message: 'token无效' })
  }
}

const adminAuth = async (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({ message: '无权限访问' })
  }
  next()
}

module.exports = { auth, adminAuth }
